package com.tfj.mvp.tfj.detail;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.tfj.R;
import com.jakewharton.rxbinding2.view.RxView;
import com.tfj.comm.bean.Constant;
import com.tfj.mvp.base.BaseActivity;
import com.tfj.mvp.tfj.detail.adapter.QuickAdapter_Addr;
import com.tfj.mvp.tfj.detail.adapter.QuickAdapter_Advisor;
import com.tfj.mvp.tfj.detail.adapter.QuickAdapter_Comment;
import com.tfj.mvp.tfj.detail.adapter.QuickAdapter_DongTai;
import com.tfj.mvp.tfj.detail.advisor.VAdvisorActivity;
import com.tfj.mvp.tfj.detail.bean.AdvisorBean;
import com.tfj.mvp.tfj.detail.bean.CommentBean;
import com.tfj.mvp.tfj.detail.bean.DongTaiBean;
import com.tfj.mvp.tfj.detail.bean.IntroBean;
import com.tfj.mvp.tfj.detail.bean.RecomBean;
import com.tfj.mvp.tfj.detail.buildinfo.VBuildInfoActivity;
import com.tfj.mvp.tfj.detail.comment.VCommentActivity;
import com.tfj.mvp.tfj.detail.dongtai.VDongTaiActivity;
import com.tfj.mvp.tfj.detail.huxing.VHuXingActivity;
import com.tfj.mvp.tfj.detail.image.VImageDetailActivity;
import com.tfj.mvp.tfj.detail.sign.VSignActivity;
import com.tfj.mvp.tfj.detail.surround.VSurroundActivity;
import com.tfj.utils.AntiShakeUtils;
import com.tfj.utils.NoScrollViewManager;
import com.tfj.utils.SysUtils;
import com.tfj.widget.RoundAngleImageView;
import com.tfj.widget.TrangleBubble;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Hq on 2017/12/21.
 *
 * @author HuangQiang
 * @github https://github.com/HuangQiang
 */

public class VDetailActivity extends BaseActivity<PDetailImpl> implements CDetail.IVDetail, PoiSearch.OnPoiSearchListener {


    @BindView(R.id.btn_video)
    Button btnVideo;
    @BindView(R.id.btn_picture)
    Button btnPicture;
    @BindView(R.id.textView_page)
    TextView textViewPage;
    @BindView(R.id.btn_back)
    ImageButton btnBack;
    @BindView(R.id.btn_toggle)
    Button btnToggle;
    @BindView(R.id.rl_toggle)
    RelativeLayout rlToggle;
    @BindView(R.id.nestView)
    NestedScrollView nestView;
    @BindView(R.id.tl_top)
    RelativeLayout tlTop;
    @BindView(R.id.recyclewView_intro)
    RecyclerView recyclewViewIntro;
    @BindView(R.id.recyclew_dongtai)
    RecyclerView recyclewDongtai;
    @BindView(R.id.recyclew_recomm)
    RecyclerView recyclewRecomm;
    @BindView(R.id.recyclewView_comment)
    RecyclerView recyclewViewComment;
    @BindView(R.id.recycleView_advisor)
    RecyclerView recycleViewAdvisor;
    @BindView(R.id.recyclew_View_addr)
    RecyclerView recyclewViewAddr;
    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.btn_bus)
    Button btnBus;
    @BindView(R.id.hospital)
    Button hospital;
    @BindView(R.id.btn_shop)
    Button btnShop;
    @BindView(R.id.btn_bank)
    Button btnBank;
    @BindView(R.id.imageView_buildinfo)
    RoundAngleImageView imageViewBuildinfo;
    @BindView(R.id.ll_map)
    LinearLayout llMap;
    @BindView(R.id.rl_huxing_intro)
    RelativeLayout rlHuxingIntro;
    @BindView(R.id.rl_dongtai)
    RelativeLayout rlDongtai;
    @BindView(R.id.rl_comment)
    RelativeLayout rlComment;
    @BindView(R.id.rl_advisor)
    RelativeLayout rlAdvisor;
    @BindView(R.id.rl_build)
    RelativeLayout rlBuild;
    @BindView(R.id.btn_baoming)
    Button btnBaoming;
    @BindView(R.id.btn_tel)
    Button btnTel;
    private AMap aMap = null;
    private boolean ifExpand = false;
    private UiSettings mUiSettings;
    private PoiSearch.Query query = null;
    private PoiSearch poiSearch = null;

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public int setContentViewId() {
        ifNeedStatus = false;
        return R.layout.activity_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        setNestBar();
        addDisposable(RxView.clicks(hospital).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    poiSearch("医院");
                    hospital.setTextColor(getResources().getColor(R.color.mainColor));
                    hospital.setBackgroundResource(R.drawable.shape_background_map_check_16);
                    btnBus.setTextColor(getResources().getColor(R.color.gray));
                    btnBus.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnShop.setTextColor(getResources().getColor(R.color.gray));
                    btnShop.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBank.setTextColor(getResources().getColor(R.color.gray));
                    btnBank.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                }));
        addDisposable(RxView.clicks(btnBus).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    poiSearch("公交");
                    hospital.setTextColor(getResources().getColor(R.color.gray));
                    hospital.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBus.setTextColor(getResources().getColor(R.color.mainColor));
                    btnBus.setBackgroundResource(R.drawable.shape_background_map_check_16);
                    btnShop.setTextColor(getResources().getColor(R.color.gray));
                    btnShop.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBank.setTextColor(getResources().getColor(R.color.gray));
                    btnBank.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);

                }));
        addDisposable(RxView.clicks(btnShop).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    poiSearch("购物");
                    hospital.setTextColor(getResources().getColor(R.color.gray));
                    hospital.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBus.setTextColor(getResources().getColor(R.color.gray));
                    btnBus.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnShop.setTextColor(getResources().getColor(R.color.mainColor));
                    btnShop.setBackgroundResource(R.drawable.shape_background_map_check_16);
                    btnBank.setTextColor(getResources().getColor(R.color.gray));
                    btnBank.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                }));
        addDisposable(RxView.clicks(btnBank).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    poiSearch("银行");
                    hospital.setTextColor(getResources().getColor(R.color.gray));
                    hospital.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBus.setTextColor(getResources().getColor(R.color.gray));
                    btnBus.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnShop.setTextColor(getResources().getColor(R.color.gray));
                    btnShop.setBackgroundResource(R.drawable.shape_background_map_uncheck_16);
                    btnBank.setTextColor(getResources().getColor(R.color.mainColor));
                    btnBank.setBackgroundResource(R.drawable.shape_background_map_check_16);
                }));
        //置业顾问
        addDisposable(RxView.clicks(rlAdvisor).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VAdvisorActivity.class);
                }));
        //楼栋详情
        addDisposable(RxView.clicks(imageViewBuildinfo).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VBuildInfoActivity.class);
                }));
        //楼栋详情
        addDisposable(RxView.clicks(rlBuild).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VBuildInfoActivity.class);
                }));
        //户型介绍
        addDisposable(RxView.clicks(rlHuxingIntro).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VHuXingActivity.class);
                }));
        //动态
        addDisposable(RxView.clicks(rlDongtai).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VDongTaiActivity.class);
                }));
        //评论
        addDisposable(RxView.clicks(rlComment).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    startActivity(VCommentActivity.class);
                }));
        addDisposable(RxView.clicks(btnVideo).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switchBanner(false);

                }));
        addDisposable(RxView.clicks(btnBack).throttleFirst(Constant.SECONDS_FORBID, TimeUnit.SECONDS)
                .subscribe(o -> {
                    VDetailActivity.this.finish();
                }));
        addDisposable(RxView.clicks(btnPicture).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    switchBanner(true);
                    startActivity(VImageDetailActivity.class);
                }));
        addDisposable(RxView.clicks(btnToggle).throttleFirst(0, TimeUnit.SECONDS)
                .subscribe(o -> {
                    btnToggle.setText(ifExpand ? "展开" : "收回");
                    rlToggle.setVisibility(ifExpand ? View.GONE : View.VISIBLE);
                    Drawable drawable = getResources().getDrawable(ifExpand ? R.mipmap.arrow_up : R.mipmap.arrow_down1);
// 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    btnToggle.setCompoundDrawables(null, null, drawable, null);
                    ifExpand = !ifExpand;
                }));
        //新房简介
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclewViewIntro.setLayoutManager(linearLayoutManager);
        recyclewViewIntro.setAdapter(quickAdapter_intro);
        List<IntroBean> introBeans = new ArrayList<>();
        introBeans.add(new IntroBean());
        introBeans.add(new IntroBean());
        introBeans.add(new IntroBean());
        introBeans.add(new IntroBean());
        quickAdapter_intro.replaceData(introBeans);
        //动态
        NoScrollViewManager noScrollViewManager = new NoScrollViewManager(this);
        noScrollViewManager.setScrollEnabled(false);
        recyclewDongtai.setLayoutManager(noScrollViewManager);
        QuickAdapter_DongTai quickAdapter_dongTai = new QuickAdapter_DongTai(this);
        recyclewDongtai.setAdapter(quickAdapter_dongTai);
        List<DongTaiBean> dongTaiBeans = new ArrayList<>();
        dongTaiBeans.add(new DongTaiBean());
        dongTaiBeans.add(new DongTaiBean());
        dongTaiBeans.add(new DongTaiBean());
        dongTaiBeans.add(new DongTaiBean());
        dongTaiBeans.add(new DongTaiBean());
        dongTaiBeans.add(new DongTaiBean());
        quickAdapter_dongTai.replaceData(dongTaiBeans);
        //为您推荐
        NoScrollViewManager noScrollViewManager_recom = new NoScrollViewManager(this);
        noScrollViewManager_recom.setScrollEnabled(false);
        recyclewRecomm.setLayoutManager(noScrollViewManager_recom);
        recyclewRecomm.setAdapter(quickAdapter_recomm);
        List<RecomBean> recomBeans = new ArrayList<>();
        recomBeans.add(new RecomBean());
        recomBeans.add(new RecomBean());
        recomBeans.add(new RecomBean());
        recomBeans.add(new RecomBean());
        recomBeans.add(new RecomBean());
        recomBeans.add(new RecomBean());
        quickAdapter_recomm.replaceData(recomBeans);
        //用户点评
        NoScrollViewManager noScrollViewManager_comment = new NoScrollViewManager(this);
        noScrollViewManager_comment.setScrollEnabled(false);
        recyclewViewComment.setLayoutManager(noScrollViewManager_comment);
        QuickAdapter_Comment quickAdapter_comment = new QuickAdapter_Comment(R.layout.item_comment);
        recyclewViewComment.setAdapter(quickAdapter_comment);
        List<CommentBean> commentBeans = new ArrayList<>();
        commentBeans.add(new CommentBean());
        commentBeans.add(new CommentBean());
        commentBeans.add(new CommentBean());
        commentBeans.add(new CommentBean());
        commentBeans.add(new CommentBean());
        quickAdapter_comment.replaceData(commentBeans);
        //职业顾问
        NoScrollViewManager noScrollViewManager_advisor = new NoScrollViewManager(this);
        noScrollViewManager_advisor.setScrollEnabled(false);
        recycleViewAdvisor.setLayoutManager(noScrollViewManager_advisor);
        QuickAdapter_Advisor quickAdapter_advisor = new QuickAdapter_Advisor(this);
        recycleViewAdvisor.setAdapter(quickAdapter_advisor);
        List<AdvisorBean> advisorBeans = new ArrayList<>();
        advisorBeans.add(new AdvisorBean());
        advisorBeans.add(new AdvisorBean());
        advisorBeans.add(new AdvisorBean());
        advisorBeans.add(new AdvisorBean());
        quickAdapter_advisor.replaceData(advisorBeans);
        //检索地址
        NoScrollViewManager noScrollViewManager_addr = new NoScrollViewManager(this);
        noScrollViewManager_addr.setScrollEnabled(false);
        recyclewViewAddr.setLayoutManager(noScrollViewManager_addr);
        recyclewViewAddr.setAdapter(quickAdapter_addr);
        initMap();
        poiSearch("公交");
    }

    private void initMap() {
        if (mapView != null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
            mUiSettings.setScaleControlsEnabled(false);//控制比例尺控件是否显示
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setCompassEnabled(false);
            mUiSettings.setRotateGesturesEnabled(false);
            mUiSettings.setAllGesturesEnabled(false);
            mUiSettings.setMyLocationButtonEnabled(false);//隐藏原有定位按钮
            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    startActivity(VSurroundActivity.class);
                }
            });
        }
    }

    private void poiSearch(String keyword) {
        query = new PoiSearch.Query(keyword, "", "");
        //默认显示三个
        query.setPageSize(3);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(119.969289, 31.818), 3000));//设置周边搜索的中心点以及半径
        poiSearch.searchPOIAsyn();//调用 PoiSearch 的 searchPOIAsyn() 方法发送请求。
        poiSearch.setOnPoiSearchListener(this);
    }

    private void setNestBar() {
        final int height = tlTop.getLayoutParams().height;
        nestView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            // 将透明度声明成局部变量用于判断
            int alpha = 0;
            float scale = 0;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY <= height) {
                    scale = (float) scrollY / height;
                    alpha = (int) (255 * scale);
                    // 随着滑动距离改变透明度
                    // Log.e("al=","="+alpha);
                    tlTop.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
                } else {
                    if (alpha < 255) {
                        // 防止频繁重复设置相同的值影响性能
                        alpha = 255;
                        tlTop.setBackgroundColor(Color.argb(alpha, 255, 255, 255));
                    }
                }
            }

        });
    }


    public void switchBanner(boolean ifPic) {
        btnPicture.setTextColor(ifPic ? getResources().getColor(R.color.white) : getResources().getColor(R.color.black));
        btnPicture.setBackgroundResource(ifPic ? R.drawable.shape_background_main_12 : R.drawable.shape_background_white_12);
        btnVideo.setTextColor(ifPic ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white));
        btnVideo.setBackgroundResource(ifPic ? R.drawable.shape_background_white_12 : R.drawable.shape_background_main_12);
    }


    @Override
    public void createPresenter() {
        mPresenter = new PDetailImpl(mContext, this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {  // 搜索poi的结果
                if (result.getQuery().equals(query)) {
                    PoiResult poiResult = result;
                    //final ArrayList<PoiAddressBean> data = new ArrayList<PoiAddressBean>();//自己创建的数据集合
                    // 取得搜索到的poiitems有多少页

                    List<PoiItem> poiItems_search = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    Log.i(TAG, JSONObject.toJSONString(poiItems_search));
                    if (poiItems_search != null && poiItems_search.size() > 0) {
                        quickAdapter_addr.replaceData(poiItems_search.size() > 3 ? poiItems_search.subList(0, 3) : poiItems_search);
                    }
                    removeAllMarker();
                    for (PoiItem item : poiItems_search) {
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        String title = item.getTitle();
                        int distance = item.getDistance();
                        addMarker(new LatLng(lat, lon), title);
                        Log.i(TAG, "title-->" + title);
                        Log.i(TAG, "distance-->" + distance + "m");
                    }
                    mList = aMap.addMarkers(markerOptionlst, false);
                    Log.i(TAG, JSONObject.toJSONString(mList));
                    aMap.moveCamera(CameraUpdateFactory
                            .newLatLngZoom(new LatLng(result.getBound().getCenter().getLongitude(), result.getBound().getCenter().getLatitude()), 13.50f));
                }
            }
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    private ArrayList<MarkerOptions> markerOptionlst = new ArrayList<MarkerOptions>();
    private List<Marker> mList = new ArrayList<Marker>();

    public void addMarker(LatLng latLng, String title) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        TrangleBubble trangleBubble = new TrangleBubble(this);
        trangleBubble.setClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(VSurroundActivity.class);
            }
        });
        trangleBubble.setText(title);
        markerOption.icon(BitmapDescriptorFactory.fromView(trangleBubble)).draggable(false);
        markerOption.visible(true);
        markerOption.setFlat(false);//设置marker平贴地图效果
        markerOptionlst.add(markerOption);
    }

    //重新刷新红包之前把之前的红包都清掉
    public void removeAllMarker() {
        if (aMap.getMapScreenMarkers().size() > 0) {
            for (int i = 0; i < aMap.getMapScreenMarkers().size(); i++) {
                aMap.getMapScreenMarkers().get(i).setVisible(false);
            }
        }
        aMap.clear();
    }

    //新房简介
    private QuickAdapter_Intro quickAdapter_intro = new QuickAdapter_Intro();

    @OnClick({R.id.btn_baoming, R.id.btn_tel})
    public void onViewClicked(View view) {
        if (AntiShakeUtils.isInvalidClick(view))
            return;
        switch (view.getId()) {
            case R.id.btn_baoming:
                startActivity(VSignActivity.class);
                break;
            case R.id.btn_tel:

                break;
        }
    }


    public class QuickAdapter_Intro extends BaseQuickAdapter<IntroBean, BaseViewHolder> {
        public QuickAdapter_Intro() {
            super(R.layout.item_intro);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, final IntroBean item) {
            LinearLayout ll_out = viewHolder.getView(R.id.ll_out);
            ViewGroup.LayoutParams layoutParams = ll_out.getLayoutParams();
            layoutParams.width = SysUtils.getWidth(VDetailActivity.this) / 2 - SysUtils.dip2px(VDetailActivity.this, 48) / 2;
            ll_out.setLayoutParams(layoutParams);
        }
    }


    //为您推荐
    private QuickAdapter_Recomm quickAdapter_recomm = new QuickAdapter_Recomm();

    public class QuickAdapter_Recomm extends BaseQuickAdapter<RecomBean, BaseViewHolder> {
        public QuickAdapter_Recomm() {
            super(R.layout.item_rank);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, final RecomBean item) {
        }
    }

    //检索结果
    private QuickAdapter_Addr quickAdapter_addr = new QuickAdapter_Addr(R.layout.item_addr);


}
